package com.module.overview.ui.cardHistoryDetails.provider

import android.util.Log
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.no
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.getString
import com.module.ble.repo.SleepInfoRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.overview.R

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/08/12
 *
 * 描述：小睡记录卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvSleepNapRecordCardProvider(time:Long,
    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_SLEEP_NAP_RECORD_PERIOD,
    override val layoutId: Int = R.layout.overview_sleep_nap_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    private var curTime = time

    private val  mAdapter by lazy { OvSleepNapRecordItemAdapter() }


    private var tvTotalDuration: TextView? = null
    private var tvNapNum: TextView? = null
    private var tvAverage: TextView? = null

    init {
    }

    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        tvTotalDuration = viewHolder.getView(R.id.tvTotalDuration)
        tvNapNum = viewHolder.getView(R.id.tvNapNum)
        tvAverage = viewHolder.getView(R.id.tvAverage)
        super.onViewHolderCreated(viewHolder, viewType)
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {
        helper.getView<RecyclerView>(R.id.hrvRecord).apply{
            adapter = mAdapter
        }
        doOnIOThread {
            SleepInfoRepo.instance.findByTimestampSameDayWithNapSleep(curTime)?.let { listIt->
                listIt.sortedBy { it.createdTime }//按时间排序（升序）

                var totalTimeLong = 0L

                listIt.forEach {
                    totalTimeLong += (it.endTime-it.createdTime)
                }

                doOnUiThread {
                    tvTotalDuration?.text = TimeUtils.formatTime(totalTimeLong, showHour = true, showMin = true)
                    tvNapNum?.text = "${listIt.size}${ViewUtils.getString(R.string.common_once_hint)}"
                    tvAverage?.text = if(totalTimeLong<=0) "0${getString(R.string.common_minutes_hint)}" else TimeUtils.formatTime((totalTimeLong/listIt.size), showHour = true, showMin = true, showSec = true)

                    listIt.isNullOrEmpty().no {
                        mAdapter.setList(listIt)
                    }
                }
            }
        }
    }
}